package url

import (
	"bytes"
	"fmt"
	"io"
	"net/http"
	"strings"
	"time"

	netUrl "net/url"

	"gitee.com/tomatomeatman/golang-repository/bricks/model"
	"gitee.com/tomatomeatman/golang-repository/bricks/utils/function/data"
	Log "github.com/cihub/seelog"
)

type HttpUtil struct{}

func (util HttpUtil) DoGet(url string, params map[string]interface{}, hears map[string]string) *model.MsgEmity {
	if nil != params {
		var temp strings.Builder
		temp.WriteString(url)
		temp.WriteString("?lt=12")

		for key, value := range params {
			temp.WriteString("&")
			temp.WriteString(key)
			temp.WriteString("=")
			temp.WriteString(fmt.Sprintf("%v", value))
		}

		url = strings.Replace(temp.String(), "lt=12&", "", 1)
	}

	client := &http.Client{}
	reqest, _ := http.NewRequest("GET", url, nil)

	if nil != hears {
		for key, value := range hears {
			reqest.Header.Add(key, value)
		}
	}

	response, err := client.Do(reqest)
	if err != nil {
		return model.MsgEmity{}.Err(1001, "请求错误:", err)
	}

	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		return model.MsgEmity{}.Err(1002, "解析页面内容错误:", err)
	}

	return model.MsgEmity{}.Success(string(body), "请求成功")
}

// 发送POST请求
func (util HttpUtil) DoPost(url string, params map[string]interface{}, hears map[string]string, isJson ...bool) *model.MsgEmity {
	var ioReader *strings.Reader
	vParams := netUrl.Values{}
	for key, val := range params {
		vParams.Set(key, fmt.Sprintf("%v", val))
	}

	// if len(params) > 0 {
	// 	ioReader = strings.NewReader(vParams.Encode())
	// } else {
	// 	ioReader = nil //必须设置,否则会错误
	// }
	ioReader = strings.NewReader(vParams.Encode()) //必须设置,否则会异常

	client := &http.Client{}
	reqest, _ := http.NewRequest("POST", url, ioReader)

	if (len(isJson) > 0) && isJson[0] {
		reqest.Header.Add("Content-Type", "application/json")
	} else {
		reqest.Header.Set("Content-Type", "application/x-www-form-urlencoded")
	}

	if nil != hears {
		for key, value := range hears {
			reqest.Header.Add(key, value)
		}
	}

	response, err := client.Do(reqest)
	if err != nil {
		Log.Error("请求访问地址发生异常:", err)
		return model.MsgEmity{}.Err(1001, "请求访问地址发生异常")
	}

	defer response.Body.Close()

	body, err := io.ReadAll(response.Body)
	if err != nil {
		Log.Error("获取请求内容发生异常:", err)
		return model.MsgEmity{}.Err(1002, "请求访问地址内容发生异常")
	}

	return model.MsgEmity{}.Success(body, "Post请求成功")
}

// func (util HttpUtil) DoPost(url string, params map[string]interface{}, hears map[string]string) *model.MsgEmity {
// 	vParams := netUrl.Values{}
// 	for key, val := range params {
// 		vParams.Set(key, fmt.Sprintf("%v", val))
// 	}

// 	var ioReader *bytes.Buffer
// 	if nil != params {
// 		bodyBytes, err := json.Marshal(params)
// 		if err != nil {
// 			return model.MsgEmity{}.Err(1001, "请求参数错误")
// 		}

// 		ioReader = bytes.NewBuffer(bodyBytes)
// 	}

// 	client := &http.Client{}
// 	reqest, _ := http.NewRequest("POST", url, ioReader)

// 	if nil != hears {
// 		for key, value := range hears {
// 			reqest.Header.Add(key, value)
// 		}
// 	}

// 	//response, err := http.PostForm(url, vParams)
// 	response, err := client.Do(reqest)
// 	if err != nil {
// 		Log.Error("请求访问地址发生异常:", err)
// 		return model.MsgEmity{}.Err(1001, "请求访问地址发生异常")
// 	}

// 	defer response.Body.Close()

// 	body, err := io.ReadAll(response.Body)
// 	if err != nil {
// 		Log.Error("获取请求内容发生异常:", err)
// 		return model.MsgEmity{}.Err(1002, "请求访问地址内容发生异常")
// 	}

// 	return model.MsgEmity{}.Success(body, "Post请求成功")
// }

func (util HttpUtil) Get(url string, jsonParams string) string {
	client := http.Client{Timeout: 10 * time.Second}

	if "" != jsonParams {
		params, err := data.JsonUtil{}.JsonToMap(jsonParams)
		if err != nil {
			fmt.Printf("Convert json to map failed with error: %+v\n", err)
		}

		var temp strings.Builder
		temp.WriteString(url)
		temp.WriteString("?lt=12")

		for key, value := range params {
			temp.WriteString("&")
			temp.WriteString(key)
			temp.WriteString("=")
			temp.WriteString(fmt.Sprintf("%v", value))
		}

		url = strings.Replace(temp.String(), "lt=12&", "", 1)
	}

	resp, err := client.Get(url)
	if err != nil {
		return model.MsgEmity{}.ErrString(9006, "请求错误:"+err.Error())
	}

	defer resp.Body.Close() // 释放对象

	// 把获取到的页面作为返回值返回
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		return model.MsgEmity{}.ErrString(9006, "请求错误:"+err.Error())
	}

	defer client.CloseIdleConnections() // 释放对象

	return model.MsgEmity{}.SuccessString(string(body), "请求成功")
}

func (util HttpUtil) Post(url string, sParams string, isJsonParams bool) string {
	contentType := "charset=utf-8"
	if isJsonParams {
		contentType = "application/json;charset=utf-8"
	}

	response, err := http.Post(url, contentType, bytes.NewBuffer([]byte(sParams)))
	if err != nil {
		return model.MsgEmity{}.ErrString(9006, "请求错误:"+err.Error())
	}

	defer response.Body.Close()
	content, err := io.ReadAll(response.Body)
	if err != nil {
		fmt.Println("Fatal error", err.Error())
	}

	return model.MsgEmity{}.SuccessString(string(content), "请求成功")
}
